package com.coffee.ws.metadata;


import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

/**
 *  byteBuffer 消息 定义的request 接口
 */
public abstract class BasicBinaryMessage<T extends BasicBinaryMessage> {

    public abstract T decode(ByteBuffer byteBuffer);

    public abstract void encode(ByteBuffer byteBuffer);

    public abstract int length();

    public ByteBuffer encode() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(this.length());
        encode(byteBuffer);
        return byteBuffer;
    }


    public void encodeString(ByteBuffer b, String v) {
        if (v == null) {
            b.putInt(0);
        } else {
            try {
                byte[] bytes = v.getBytes("UTF-8");
                b.putInt(bytes.length);
                b.put(bytes);
            } catch (UnsupportedEncodingException var3) {
                b.putInt(0);
            }

        }
    }

    public String decodeString(ByteBuffer b){
        int length = b.getInt();
        if (length <= 0) {
            return null;
        } else if (b.limit() < length) {
            return null;
        } else {
            byte[] bytes = new byte[length];
            b.get(bytes);
            try {
                return new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException var4) {
                return null;
            }
        }
    }


}
